<?php

namespace App\Http\Controllers\Admin\Setting\Wechat;

use App\Http\Controllers\Admin\Controller;
use App\Models\WechatConfig;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Inertia\Response;

class WeChatConfigController extends Controller
{
    public function index(): Response
    {
        $wechat_config = WechatConfig::query()->first();
        if (!$wechat_config){
            $wechat_config = $this->initWechatConfig();
        }
        return $this->inertia('setting/wechat/config/index',[
            'data' => $wechat_config,
        ]);
    }

    public function initWechatConfig()
    {
        return WechatConfig::query()->create([
            'app_id' => '',
            'secret' =>  '',
            'token' =>  '',
            'aes_key' => '',
            'app_callback_url' =>  'https://www.xxxx.com/api/wechat-official-notify',
            'use_stable_access_token' =>  false,
        ]);
    }

    /**
     * @throws ValidationException
     */
    public function update(Request $request): RedirectResponse
    {
        $params = $this->validate(
            $request,
            [
                'app_id' => 'required|string',
                'secret' => 'required|string',
                'token' => 'required|string',
                'aes_key' => 'nullable|string',
                'app_callback_url' => 'nullable|string',
                'use_stable_access_token' => 'nullable|boolean',
            ],
            [
                'app_id.*' => '请输入应用ID',
                'secret.*' => '请输入应用密钥',
                'token.*' => '请输入令牌',
                'aes_key.*' => '请输入AES密钥',
                'app_callback_url.*' => '请输入应用回调URL',
                'use_stable_access_token.*' => '请输入是否使用稳定的访问令牌',
            ]
        );
        $wechat_config = WechatConfig::query()->first();
        $wechat_config->update($params);
        return redirect()->route('admin.setting.wechat.configs.index');
    }
}
